<?php


namespace App\server;


use Elasticsearch\ClientBuilder;

class EsServer
{
    protected $client;
    public function __construct()
    {
        $hosts = [
            //config('es.hosts'),
            '127.0.0.1:9200',     // IP + Port
        ];
        $client = ClientBuilder::create()  // Instantiate a new ClientBuilder
        ->setHosts($hosts)      // Set the hosts
        ->build();
        return $this->client = $client;
    }
    /**
     * 添加
     */
    public function EsAdd($indexName,$indexAll)
    {
        $params = [
            'index' => $indexName,
            'id'    => $indexAll['id'],
            'body'  => $indexAll
        ];
        $this->client->index($params);
    }
    /**
     * 同步数据库数据
     * @param $index
     * @param $data
     */
    public function EsAddOne($index,$data){
        foreach ($data as $item => $v){
            $params=[
                'index' => $index,
                'id'    => $v['id'],
                'body'=>$v
            ];
            $res= $this->client->index($params);
        }
        return $res;
    }
    /**
     * 搜索
     * $indexName 索引名字
     * $indexAll  搜索内容
     * $field   搜索字段
     */
    public function searchEs($indexName,$indexAll,$field)
    {
        //做检索
        $params = [
            'index' => $indexName,
            'body'  => [
                //查询条件
                'query' => [
                    'match'=>[
                        $field => $indexAll
                    ],
                ],
                //高亮显示
                'highlight'=>[
                    "pre_tags"=>["<span style='color: red'>"],
                    "post_tags"=>["</span>"],
                    "fields"=>["fang_name"=>new \stdClass()]
                ]
            ],
        ];
        $response=$this->client->search($params);//提取出想要的数据
        $data=$response['hits']['hits'];
        foreach ($data as $v){
            $datas[] = $v['_source'];
        }
        return $datas;
    }
    /**
     * 查询全部数据
     * $indexName 索引名字
     */
    public function EsAll($indexName)
    {
        $params = [
            'index' => $indexName,
            'body'  => [
            ],
        ];
        $response=$this->client->search($params);//提取出想要的数据
        $data=$response['hits']['hits'];
        foreach ($data as $v){
            $datas[] = $v['_source'];
        }
        return $datas;
    }
     /**
     * 删除索引
     * @param $index
     * @param $data
     */
    public function EsDel($index){
        $deleteParams = [
            'index' => $index
        ];
        $res= $this->client->delete($deleteParams);
        return $res;
    }
}
